package com.hjq.widget.view

import android.content.Context
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import androidx.appcompat.widget.AppCompatImageView
import androidx.core.content.ContextCompat
import androidx.core.view.setPadding
import com.hjq.widget.R

/**
 * 控制密码显隐性按钮
 */
class ShowPasswordButton @JvmOverloads constructor(context: Context, attributeSet: AttributeSet? = null, defStyleAttr: Int = 0) :
    AppCompatImageView(context, attributeSet, defStyleAttr) {
    private var isShowPassword: Boolean = false
    private var hideDrawable: Drawable?
    private var showDrawable: Drawable?

    init {
        val attr = context.obtainStyledAttributes(attributeSet, R.styleable.ShowPasswordButton, defStyleAttr, 0)
        hideDrawable = attr.getDrawable(R.styleable.ShowPasswordButton_hideImg) ?: ContextCompat.getDrawable(context, R.drawable.login_hide_password)
        showDrawable =
            attr.getDrawable(R.styleable.ShowPasswordButton_showImg) ?: ContextCompat.getDrawable(context, R.drawable.register_show_password)
        attr.recycle()
        setPadding(resources.getDimensionPixelSize(R.dimen.show_password_btn_padding))
        scaleType = ScaleType.FIT_CENTER
        setImageDrawable(hideDrawable)
    }

    fun setPasswordEdit(passwordEdit: EditText?) {
        setOnClickListener {
            passwordEdit?.apply {
                isShowPassword = !isShowPassword
                inputType = if (isShowPassword)
                    EditorInfo.TYPE_CLASS_TEXT or EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
                else EditorInfo.TYPE_CLASS_TEXT or EditorInfo.TYPE_TEXT_VARIATION_PASSWORD
                setImageDrawable(if (isShowPassword) showDrawable else hideDrawable)
                setSelection(length())
            }
        }
    }
}